#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import os.path
import sys
import struct
import collections

### ADD PATH
__current_dir__ = os.path.realpath(os.path.dirname(__file__))

admin_path = os.path.realpath('%s/../../admin' % __current_dir__)
sys.path.insert(0, admin_path)

for i in sys.path:
    # print 'path %s' % i
    pass


from buddha.utils import _exec_pipe1


def f_name(volid, chunk_id):
    return 'raw.%d.%d.dump' % (volid, chunk_id)



VOLUME_TYPE = 'volume'
SNAP_TYPE   = 'snap'


def download_raw(volid, chunk_id):
    fname = f_name(volid, chunk_id)
    if os.path.isfile(fname):
        return

    cmd = 'lich.inspect --chunkdump raw.%d.%d' % (volid, chunk_id)
    os.system(cmd)


def run_cmd(cmd):
    out, msg = _exec_pipe1(['ls', '-lh'])
    l = [x.strip(' \t') for x in out.split('\n')]
    return [x for x in l if x]


def parse_path(path, typ):
    if typ == VOLUME_TYPE:
        l = path.split('/')
        l = [x for x in l if x]
        assert len(l) == 3
        return l, None
    elif typ == SNAP_TYPE:
        l = path.split('@')
        assert len(l) == 2
        l2 = parse_path(l[0], VOLUME_TYPE)
        return l2[0], l[1]


class LichInspct(object):
    def __init__(self):
        pass

    def chunkinfo(self, pool, chkid):
        return run_cmd(['lich.inspect', '--chunkinfo', chkid, '--pool', pool])

    def chunkdump(self, pool, chkid):
        return run_cmd(['lich.inspect', '--chunkdump', chkid, '--pool', pool])


class LichBD(object):
    def __init__(self):
        pass

    def vol_info(self, path):
        lines = run_cmd(['lichbd', 'vol', 'info', path])
        return lines

    def list_snap(self, path):
        return run_cmd(['lichbd', 'snap', 'ls', path])


def test1():
    pass


if __name__ == '__main__':
    print parse_path('/a/b/c', VOLUME_TYPE)
    print parse_path('/a/b/c@d', SNAP_TYPE)
